package com.wjerp.tplus.server.api.controller;


import ch.qos.logback.core.util.SystemInfo;
import com.wjerp.tplus.server.api.controller.base.BaseController;
import com.wjerp.tplus.server.api.request.FieldValueRequest;
import com.wjerp.tplus.server.api.request.QueryUserListRequest;
import com.wjerp.tplus.server.api.response.FieldValueResponse;
import com.wjerp.tplus.server.application.biz.SystemManageBiz;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.model.*;
import com.wjerp.tplus.server.common.security.JwtUser;
import com.wjerp.tplus.server.domain.entity.sys.*;
import com.wjerp.tplus.server.domain.service.PermissionInfoService;
import com.wjerp.tplus.server.domain.service.SystemInfoService;
import com.wjerp.tplus.server.domain.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 管理端——系统管理
 * @author lishuailei
 */
@Api(tags = "管理端--系统管理",description="管理端--系统管理相关api")
@RestController
@RequestMapping("sys")
public class SystemManage extends BaseController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private SystemManageBiz systemManageBiz;

    @Resource
    private PermissionInfoService permissionInfoService ;

    @Resource
    private SystemInfoService systemInfoService;

    @ApiOperation("用户管理——新增用户")
    @RequestMapping(value="addUser", method= RequestMethod.POST)
    public ResponseEntity<BaseResponseData> register(
            @ApiParam(value="添加系统用户请求参数，其中permissionId以逗号分割")
            @RequestBody SystemUserWrapper systemUserWrapper){
        try {
            JwtUser currentLoginUserInfo = getCurrentLoginUserInfo();
            systemUserWrapper.setCompanyCode(currentLoginUserInfo.getCompanyCode());
            userInfoService.createSystemUser(systemUserWrapper,currentLoginUserInfo);
            return success("用户创建成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("用户管理——编辑用户")
    @RequestMapping(value="user/{userId}", method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> editSystemUser(
            @ApiParam(value="用户ID")
            @PathVariable Long userId,
            @ApiParam(value="编辑用户请求参数,其中permissionIds以逗号分割")
            @RequestBody   SystemUserWrapper systemUserWrapper){
        try {
            JwtUser currentLoginUserInfo = getCurrentLoginUserInfo();
            userInfoService.updateSystemUser(userId,systemUserWrapper,currentLoginUserInfo);
            return success("用户修改成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("用户管理——重置登陆密码")
    @RequestMapping(value="resetUserPwd/{displayUserId}", method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> resetUserPassword(
            @ApiParam(value="用户显示ID")
            @PathVariable  String displayUserId){
        try {
            userInfoService.resetUserPassword(displayUserId);
            return success("用户密码已重置");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }


    @ApiOperation("用户管理--分页查询")
    @PostMapping("userList")
    public ResponseEntity<BaseResponseData> findUserList(
            @RequestBody QueryUserListRequest queryUserListRequest
    ){
        List<String> createdTimeRangeList =  queryUserListRequest.getCreatedTimeRange();
        String startDate = formatDate("",0);
        String endDate = formatDate("",1);
        if(!CollectionUtils.isEmpty(createdTimeRangeList)){
            startDate = formatDate(createdTimeRangeList.get(0),0);
            endDate = formatDate(createdTimeRangeList.get(1),1);
        }

        Map<String,Object> resultMap=userInfoService.findSystemUserListByPage(
                queryUserListRequest.getName(),
                queryUserListRequest.getUserName(),
                queryUserListRequest.getStatus(),
                startDate,
                endDate,
                queryUserListRequest.getCurrent(),
                queryUserListRequest.getPageSize(),1);
        return success(resultMap);

    }

    @ApiOperation("用户管理——用户冻结")
    @PutMapping("disabled/{userId}")
    public ResponseEntity<BaseResponseData> disabledUser(
            @ApiParam(value="用户显示ID")
            @PathVariable  String userId
    ){
        try {
            userInfoService.updateUserStatus(userId,false);
            return success(true);
        }catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }


    @ApiOperation("用户管理——用户启用")
    @PutMapping("enabled/{userId}")
    public ResponseEntity<BaseResponseData> enabledUser(
            @ApiParam(value="用户显示ID")
            @PathVariable  String userId
    ){
        try {
            userInfoService.updateUserStatus(userId,true);
            return success(true);
        }catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("用户管理——详细信息（根据用户ID查询）")
    @GetMapping("user/{userId}")
    public ResponseEntity<BaseResponseData> findByMerchant(
            @ApiParam(value="用户显示ID")
            @PathVariable  String userId
    ){
        try {
            UserInfo userInfo= userInfoService.findUserInfoByDisplayUserId(userId);
            return success(userInfo);
        }catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("用户管理——权限分配")
    @RequestMapping(value="distributionPermissionByUser/{userId}",method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> distributionPermissionByUser(
            @ApiParam(value="用户ID")
            @PathVariable  Long userId,
            @ApiParam(value="用户权限分配关系")
            @RequestBody   List<UserPermission> userPermissions){
        try {
            userInfoService.distributionPermissionByUser(userId,userPermissions);
            return success("用户权限分配成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }


    @ApiOperation("权限管理——获取所有的角色名称")
    @GetMapping("loadRoleList")
    public ResponseEntity<BaseResponseData> loadRoleList(){
        List<RoleInfoResponseData> roleInfoList= systemManageBiz.loadAllRole();
        return success(roleInfoList);
    }

    @ApiOperation("权限管理——新增角色")
    @RequestMapping(value="addRole", method= RequestMethod.POST)
    public ResponseEntity<BaseResponseData> createRole(
            @ApiParam(value="添加角色请求参数")
            @RequestBody   RoleInfoWrapper roleInfoWrapper){
        try {
            systemManageBiz.createRole(roleInfoWrapper);
            return success("用户创建成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("权限管理——编辑角色")
    @RequestMapping(value="role/{roleId}", method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> editRole(
            @ApiParam(value="角色ID")
            @PathVariable  Long roleId,
            @ApiParam(value="编辑角色请求参数")
            @RequestBody   RoleInfoWrapper roleInfoWrapper){
        try {
            roleInfoWrapper.setId(roleId);
            systemManageBiz.updateRole(roleInfoWrapper);
            return success("角色修改成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("权限管理——删除角色")
    @RequestMapping(value="deleteRole/{roleId}", method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> deleteRole(
            @ApiParam(value="角色ID")
            @PathVariable  Long roleId){
        try {
            systemManageBiz.deleteRole(roleId);
            return success("角色删除成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("权限管理——获取所有的权限信息")
    @GetMapping("loadPermissionList")
    public ResponseEntity<BaseResponseData> findPermissionList(){
        List<PermissionInfo> permissionInfoList=systemManageBiz.findPermissionList();
        return success(permissionInfoList);
    }

    @ApiOperation("权限管理——根据用户ID获取可以配置的权限")
    @GetMapping("loadPermissionListByUserId/{userId}")
    public ResponseEntity<BaseResponseData> findPermissionListByUserId(
            @PathVariable(value = "userId") Long userId){
        try {
            List<PermissionInfo> permissionInfoList=systemManageBiz.findPermissionListByUserId(userId);
            //获取基础权限信息
            List<UserPermission> baseUserPermissionList = systemManageBiz.findBasePermissionListByUserId(userId);
            List<PermissionInfo> resultPermissionInfoList = new ArrayList<>();
            for (PermissionInfo permissionInfo : permissionInfoList){
               Long count = baseUserPermissionList.stream().filter(p->p.getPermission().equalsIgnoreCase(permissionInfo.getName())).count();
                if(count!=null && count>0){

                }else{
                    resultPermissionInfoList.add(permissionInfo);
                }
            }
            return success(resultPermissionInfoList);
        }catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("权限管理——根据角色获取可以配置的权限")
    @GetMapping("loadPermissionListByRoleId/{roleId}")
    public ResponseEntity<BaseResponseData> findPermissionListByRoleId(@PathVariable(value = "roleId") Long roleId){
        List<PermissionInfo> permissionInfoList=permissionInfoService.findPermissionListByRoleId(roleId);
        return success(permissionInfoList);
    }

    @ApiOperation("权限管理——角色权限分配")
    @RequestMapping(value="distributionPermissionByRole/{roleId}",method= RequestMethod.PUT)
    public ResponseEntity<BaseResponseData> distributionPermissionByRole(
            @ApiParam(value="角色ID")
            @PathVariable  Long roleId,
            @ApiParam(value="角色权限分配关系信息")
            @RequestBody   List<RolePermissionRelation> rolePermissionRelations){
        try {
            systemManageBiz.distributionPermission(roleId,rolePermissionRelations);
            return success("角色权限分配成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

    @ApiOperation("系统配置")
    @PostMapping(value="updateConfig")
    public ResponseEntity<BaseResponseData> updateSystemConfig(
            @ApiParam(value="配置信息")
            @RequestBody FieldValueRequest request){
        JwtUser currentLoginUserInfo = getCurrentLoginUserInfo();
        systemInfoService.updateSystemConfig(request,currentLoginUserInfo.getCompanyCode(),currentLoginUserInfo.getDisplayUserId());
        return success("配置信息成功");
    }

    @ApiOperation("获取系统配置信息")
    @GetMapping(value="loadConfigInfo")
    public ResponseEntity<BaseResponseData> loadSysConfigInfo(){
        JwtUser currentLoginUserInfo = getCurrentLoginUserInfo();
        FieldValueResponse fieldValueResponse = systemInfoService.loadSysConfigInfoByCompanyCode(currentLoginUserInfo.getCompanyCode());
        return success(fieldValueResponse);
    }



}
